package aiball

import grails.plugins.springsecurity.SpringSecurityService;
import org.springframework.dao.DataIntegrityViolationException;
import grails.plugins.springsecurity.Secured;
import components.PlayerCompiler;
import components.SecurityParser;

class PlayerController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
	def springSecurityService
	@Secured(['ROLE_ADMIN'])
	def upload() {
		def uploadedFile = request.getFile('payload');
		def cont = "";
		def thisLine = "";
		InputStream fin =  uploadedFile.getInputStream();
		// JDK1.1+
		BufferedReader myInput = new BufferedReader
			(new InputStreamReader(fin));
		while ((thisLine = myInput.readLine()) != null) {
		   cont += thisLine + "\n";
		   }
		render(cont)
	}
	
	@Secured(['ROLE_USER', 'ROLE_ADMIN'])
    def index() {
        redirect(view: "index")
    }
	
	@Secured(['ROLE_ADMIN'])
    def list() {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [playerInstanceList: Player.list(params), playerInstanceTotal: Player.count()]
    }
	@Secured(['ROLE_ADMIN'])
    def create() {
        [playerInstance: new Player(params)]
    }
	@Secured(['ROLE_USER', 'ROLE_ADMIN'])
    def save() {
        def playerInstance = new Player(params)
		
        if (!playerInstance.save(flush: true)) {
            render(view: "create", model: [playerInstance: playerInstance])
            return
        }

		flash.message = message(code: 'default.created.message', args: [message(code: 'player.label', default: 'Player'), playerInstance.id])
        redirect(action: "show", id: playerInstance.id)
		
    }
	@Secured(['ROLE_USER', 'ROLE_ADMIN'])
    def show() {
        def playerInstance = Player.get(params.id)
        if (!playerInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'player.label', default: 'Player'), params.id])
            redirect(action: "index")
            return
        }
		def playerStatsInstanceList = PlayerStats.list(params)
        [playerInstance: playerInstance, playerStatsInstanceList: playerStatsInstanceList]
    }
	@Secured(['ROLE_USER', 'ROLE_ADMIN'])
    def edit() {
        def playerInstance = Player.get(params.id)
	if (playerInstance!=((UserAccount)springSecurityService.getCurrentUser()).getTeam().getPlayer1())
	if (playerInstance!=((UserAccount)springSecurityService.getCurrentUser()).getTeam().getPlayer2())
	if (playerInstance!=((UserAccount)springSecurityService.getCurrentUser()).getTeam().getPlayer3())
	if (playerInstance!=((UserAccount)springSecurityService.getCurrentUser()).getTeam().getPlayer4())
	if (playerInstance!=((UserAccount)springSecurityService.getCurrentUser()).getTeam().getPlayer5())
	if(!springSecurityService.getPrincipal().getAuthorities().toString().equals("[ROLE_ADMIN]"))
	redirect(action: "list")
        if (!playerInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'player.label', default: 'Player'), params.id])
            redirect(action: "index")
            return
        }

        [playerInstance: playerInstance]
    }
	@Secured(['ROLE_USER', 'ROLE_ADMIN'])
    def update() {
        def playerInstance = Player.get(params.id)
		if (playerInstance!=((UserAccount)springSecurityService.getCurrentUser()).getTeam().getPlayer1())
		if (playerInstance!=((UserAccount)springSecurityService.getCurrentUser()).getTeam().getPlayer2())
		if (playerInstance!=((UserAccount)springSecurityService.getCurrentUser()).getTeam().getPlayer3())
		if (playerInstance!=((UserAccount)springSecurityService.getCurrentUser()).getTeam().getPlayer4())
		if (playerInstance!=((UserAccount)springSecurityService.getCurrentUser()).getTeam().getPlayer5())
		if(!springSecurityService.getPrincipal().getAuthorities().toString().equals("[ROLE_ADMIN]"))
		redirect(action: "list")
		def comp = new CompilerService();

		String compilerOutput = comp.compileAndParse(playerInstance, params.get("sourceCode"));
		
			
		if(compilerOutput.isEmpty())
		{
        if (!playerInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'player.label', default: 'Player'), params.id])
            redirect(action: "list")
            return
        }

        if (params.version) {
            def version = params.version.toLong()
            if (playerInstance.version > version) {
                playerInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'player.label', default: 'Player')] as Object[],
                          "Another user has updated this Player while you were editing")
                render(view: "edit", model: [playerInstance: playerInstance])
                return
            }
        }

        playerInstance.properties = params

			
        if (!playerInstance.save(flush: true)) {
            render(view: "edit", model: [playerInstance: playerInstance])
            return
        }
		
		
		comp.generateLineupXML(comp.findTeamToPlayer(playerInstance));
		
		flash.message = message(code: 'default.updated.message', args: [message(code: 'player.label', default: 'Player'), playerInstance.id])
        redirect(action: "show", id: playerInstance.id)
		}
		else
		{
			render("<h1>Compilation / Parse Error:</h1><br><pre>" + compilerOutput + "</pre>");
			return
		}
    }

    
	

	
	def showOtherTeam(){
		def playerInstance = Player.get(params.id)
		if (!playerInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'player.label', default: 'Player'), params.id])
			redirect(action: "list")
			return
		}
		def playerStatsInstanceList = PlayerStats.list(params)
		[playerInstance: playerInstance, playerStatsInstanceList: playerStatsInstanceList]
	}
}
